package com.zhubayi.springcloud.controller;

import com.zhubayi.springcloud.entities.CommonResult;
import com.zhubayi.springcloud.entities.Payment;
import com.zhubayi.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhubayi
 */
@Slf4j
@RestController
@RequestMapping("payment")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private DiscoveryClient discoveryClient;
    @GetMapping("list")
    public CommonResult list(){
        CommonResult<List<Payment>> commonResult = new CommonResult<>();
        commonResult.setCode(200);
        commonResult.setMessage("success"+serverPort);
        commonResult.setData(paymentService.findAll());
        return commonResult;
    }
    @PostMapping("create")
    public CommonResult create(@RequestBody Payment payment){
        int res = paymentService.create(payment);
        log.info("***插入结果***{}",res);
        if(res>0){
           return   new CommonResult(200,"插入成功,端口:"+serverPort);
        }
        return   new CommonResult(444,"插入失败");
    }
    @GetMapping("get/{id}")
    public CommonResult get(@PathVariable("id") Long id){
        Payment payment= paymentService.getPaymentById(id);
        if(payment!=null){
            return   new CommonResult(200,"查询成功，端口:"+serverPort,payment);
        }
        return   new CommonResult(444,"查询失败,端口："+serverPort);
    }
    @GetMapping("discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("*****element****{}",service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }
    @GetMapping("/lb")
    public String getPaymentLB(){
        return serverPort;
    }
    @GetMapping("feignTimeout")
    public String paymentFeignServiceTimeout(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "success 端口:"+serverPort;
    }
    @GetMapping("/zipkin")
    public String paymentZipkin()
    {
        return "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~";
    }
}
